<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加网站"
    :close-on-click-modal="false"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="网站名称" prop="name">
        <el-input v-model="form.name" placeholder="例如：公司官网" />
      </el-form-item>
      <el-form-item label="域名" prop="domain">
        <el-input v-model="form.domain" placeholder="例如：example.com" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="网站描述（可选）"
          style="resize: none"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="isLoading">
        创建
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  visible: boolean
  isLoading?: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  submit: [values: any]
}>()

const dialogVisible = ref(props.visible)
const formRef = ref<FormInstance>()
const form = ref({
  name: '',
  domain: '',
  description: ''
})

const rules: FormRules = {
  name: [
    { required: true, message: '请输入网站名称', trigger: 'blur' }
  ],
  domain: [
    { required: true, message: '请输入域名', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9][a-zA-Z0-9-_.]*\.[a-zA-Z0-9-_.]+$/, 
      message: '请输入有效的域名', 
      trigger: 'blur' 
    }
  ]
}

watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
})

watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  form.value = {
    name: '',
    domain: '',
    description: ''
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      emit('submit', { ...form.value })
      handleClose()
    }
  })
}
</script>

<style scoped lang="scss">
// 样式可以在这里添加
</style>

